package com.szxw.BaiduAi.service;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import com.szxw.BaiduAi.factory.ApiFactory;
import com.szxw.BaiduAi.utils.FileUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Author: 苏执小威
 * @Email:1410511702@qq.com
 * @Desc: 人脸识别的服务层用于处理业务
 * @Date: 2022/9/22 14:53
 */
public class FaceService {

    public FaceService(){}
    //通过ApiFactory得到实例化结果
    private static AipFace client = ApiFactory.getFaceInstance();

    private static HashMap<String, String> options = new HashMap<String, String>();

    /**
     * 该方法用于实现 人脸检测功能
     * @param formData
     * @param types
     * @return
     */
    public static JSONObject detect(byte[] formData ,String[] types){
        String type = "";
        for (int i = 0; i < types.length ; i++) {
            if( i <  types.length-1){
                type += types[i];
                type += ",";
            }
            type += types[i];
        }
        options.put("face_field", type);
        options.put("max_face_num", "1");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");

        String image = Base64Util.encode(formData);
        String imageType = "BASE64";
        return client.detect(image,imageType,options);
    }

    /**
     * 该方法用于实现 人脸对比功能
     * @param
     * @param
     * @param image1
     * @param image2
     * @return
     */
    public static JSONObject match(byte[] image1 , byte[] image2){

        String images1 = Base64Util.encode(image1);
        String images2 = Base64Util.encode(image2);
        MatchRequest req1 = new MatchRequest(images1, "BASE64");
        MatchRequest req2 = new MatchRequest(images2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        return client.match(requests);
    }
}
